import { drawerFormState, operateType } from "../store";
import { Button } from "ant-design-vue";
import styles from "./index.module.less";
import { Teleport } from "vue";
import {
  drinkMap,
  educationalMap,
  eyeColorMap,
  hairColorMap,
  intentionMap,
  monthIncomeMap,
  occupationCatesDict,
  popularOptions,
  punchMap,
  raceMap,
  scoreOptions,
  skinColorMap,
  smokeMap,
  tattooMap,
  vipOptions,
} from "../dict";
import { tmp_account_picture, tmp_tag_ids } from "../utils";
import { calculateAge } from "./utils";
export default defineComponent({
  emits: ["close"],
  setup(props, { emit }) {
    const isLoad = ref(false); // H5是否加载完成
    const iframeRef: any = ref(null);
    const receiveParentWindowMessage = (e: any) => {
      if (e.data.type === "loadComplete") sendMsg(drawerFormState);
    };
    const sendMsg = (formState: any) => {
      const dynamicIds =
        operateType.value === "view"
          ? [...formState.dynamics]
          : [...formState.userDynamics]; // 个人动态
      const occupation_id = formState?.occupation_id?.split?.("/") ?? [];
      const messageData = {
        type: "updateUserInfo",
        data: JSON.parse(
          JSON.stringify({
            userInfo: {
              ...formState,
              intention: isArray(formState?.intention)
                ? formState.intention?.join?.(",")
                : formState.intention,
              city: formState?.city || "",
              country: formState?.country || "",
              tags: tmp_tag_ids.value.map((item) => ({
                ...item,
                color: "#EEC89F",
                tag_name_en: item.tag_name,
              })),
              account_picture: tmp_account_picture.value,
              tag_ids: tmp_tag_ids.value,
              age: isString(formState.birthday)
                ? calculateAge(formState.birthday)
                : calculateAge(formState.birthday.format("YYYY-MM-DD")),
              birthday: isString(formState.birthday)
                ? formState.birthday
                : formState.birthday.format("YYYY-MM-DD"),
              popular_level:
                formState.popular_level === undefined
                  ? 0
                  : formState.popular_level,
              score_level:
                formState.score_level === undefined ? 0 : formState.score_level,
              vip_level:
                formState.vip_level === undefined ? 0 : formState.vip_level,
              constellation_en: formState.constellation,
              drink: formState.drink === undefined ? 0 : formState.drink,
              eye_color:
                formState.eye_color === undefined ? 0 : formState.eye_color,
              hair_color:
                formState.hair_color === undefined ? 0 : formState.hair_color,
              race: formState.race === undefined ? 0 : formState.race,
              punch: formState.punch === undefined ? 0 : formState.punch,
              smoke: formState.smoke === undefined ? 0 : formState.smoke,
              height: formState.height === undefined ? 0 : formState.height,
              weight: formState.weight === undefined ? 0 : formState.weight,
              [formState?.social_account_type ?? formState.socialAccountType]:
                formState.social_account,
              social_account_type:
                formState?.social_account_type ?? formState.socialAccountType,
              socialAccountType:
                formState?.social_account_type ?? formState.socialAccountType,
              occupation_post_name: occupation_id[1],
              occupation_cate: occupationCatesDict.value?.find(
                ({ value, label }) => occupation_id[0] === label
              )?.value,
              userDynamics: formState.userDynamics,
              country_code: formState.country_code,
              location: formState.location,
              lat: formState.lat,
              long: formState.long,
              verify_video: formState.verify_video ?? formState.video,
              occupation_post: formState.occupation_post,
              dynamicIds: formState.dynamicIds,
            }, // 个人信息
            dynamics: dynamicIds.map((item) => ({
              ...item,
              created_at: new Date(),
              pictures: item?.pictures ?? [],
              type: item.video ? 2 : 1,
            })), // 个人动态
            dict: {
              memberType: vipOptions.value.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              popularLevel: popularOptions.value.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              memberBenefits: [],
              scoreLevel: scoreOptions.value.map((item: any) => ({
                ...item,
                id: item.value,
                name: item.label,
              })),
              educationMap: educationalMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              monthIncomeMap: monthIncomeMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              hair_color_map: hairColorMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              eye_color_map: eyeColorMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              skin_color_map: skinColorMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              punch_map: punchMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              tattoo_map: tattooMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              race_map: raceMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              smoke_map: smokeMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              drink_map: drinkMap.map((item: any) => ({
                value: item.value,
                title: item.label,
              })),
              intention_map: intentionMap.value.map((item: any) => ({
                id: item.value,
                name: item.label,
              })),
            }, // 字典
          })
        ),
      };
      iframeRef.value.contentWindow.postMessage(messageData, "*");
    };
    watch(
      [
        () => drawerFormState,
        () => tmp_account_picture.value,
        () => tmp_tag_ids.value,
      ],
      () => {
        // 通知iframe更新数据
        if (isLoad.value) sendMsg(drawerFormState);
      },
      {
        deep: true,
      }
    );
    onMounted(() => {
      iframeRef.value.onload = () => (isLoad.value = true);
      window.addEventListener("message", receiveParentWindowMessage);
    });
    onUnmounted(() =>
      window.removeEventListener("message", receiveParentWindowMessage)
    );
    try {
      return () => (
        <>
          <Teleport to="body">
            <div class={styles.im_h5_style}>
              <iframe
                ref={iframeRef}
                name="iframeName"
                src={import.meta.env.VITE_H5 + "/userInfoForBackstage"}
                frameborder="0"
                style="width:100%; height: 100%;"
              />

              <div class={styles.button}>
                <Button onClick={() => emit("close")}>
                  {$t("base.closePreview")}
                </Button>
              </div>
            </div>
          </Teleport>
        </>
      );
    } catch (error: any) {
      console.log(error);
    }
  },
});
